#-------------------------------------------------------------------------------
# Name:       mutex
# Purpose:
#
# Author:     SUPER_紫电  QQ,911344755
#
# Created:    15/09/2022
# Copyright:  (c) SUPER_紫电 2022 All rights reserved.
# Licence:    <Modified BSD License>
#-------------------------------------------------------------------------------

import win32api, win32event, winerror

mutex_handle = None

def create_mutex(name):
    global mutex_handle
    mutex_handle = win32event.CreateMutex(None, True, name)
    if win32api.GetLastError() == winerror.ERROR_ALREADY_EXISTS:
        return False
    return int(mutex_handle) > 0

def exist_mutex(name):
    _handle = win32event.CreateMutex(None, 0, name)
    #_handle = win32event.OpenMutex(1, 0, name)
    if win32api.GetLastError() == winerror.ERROR_ALREADY_EXISTS:
        return True
    if int(_handle) > 0:
        #win32event.ReleaseMutex(_handle)
        win32api.CloseHandle(_handle)
    return False

def release_mutex():
    global mutex_handle
    if int(mutex_handle) > 0:
        win32event.ReleaseMutex(mutex_handle)
        win32api.CloseHandle(mutex_handle)

